package com.group.yqxxb.util;

import com.alibaba.fastjson.JSONObject;
import com.group.yqxxb.builder.CheckSumBuilder;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;

import javax.swing.*;
import java.io.IOException;
import java.util.Date;


/**
 * 调用网易云信api的工具类
 */
public class ApiUtil {
    /**
     * 由于网易云信的请求都是post请求，所以这里返回HttpPost
     */
    public HttpPost BuildHeader(String url){
        //创建post请求
        HttpPost httpPost = new HttpPost(url);

        //请求头的内容
        String appKey = "14d25526d8e5c52ffdf46440931d3f48";
        String appSecret = "b2707e7576e7";
        //随机字符串
        String nonce = "dxy2013";
        //当前UTC时间戳，从1970年1月1日0点0 分0 秒开始到现在的秒数(String)
        //getTime 获取时间的毫秒数
        String curTime = String.valueOf((new Date()).getTime()/1000L);
        String checkSum = CheckSumBuilder.getCheckSum(appSecret,nonce,curTime);
        System.out.println(curTime);
        System.out.println(checkSum);

        // 设置请求的header
        httpPost.addHeader("AppKey", appKey);
        httpPost.addHeader("Nonce", nonce);
        httpPost.addHeader("CurTime", curTime);
        httpPost.addHeader("CheckSum", checkSum);
        httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        return httpPost;
    }

    /**
     * api返回的都是Json这里返回JsonObject便于格式转换
     * 用DefaultHttpClient这种方式获取httpClient已经淘汰了
     * HttpEntity 里面存储响应内容
     * @return JsonObject
     */
    public JSONObject ApiResponse(HttpPost httpPost) throws IOException {
//        DefaultHttpClient httpClient = new DefaultHttpClient();
        HttpClient httpClient = HttpClientBuilder.create().build();
        //执行请求
        HttpResponse httpResponse = httpClient.execute(httpPost);
        String resultString = EntityUtils.toString(httpResponse.getEntity(),"utf-8");
        JSONObject result = JSONObject.parseObject(resultString);
        return result;
    }


}
